package json;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class testJson {
    @Test
    public void test() {
        Student student = new Student(21222, "wuji", "nan", 23);
        String jsonStr = JSONUtil.toJsonStr(student);
        System.out.println(jsonStr);
    }
    @Test
    public void test2() {
        String a="{\"sno\":21222,\"sname\":\"wuji\",\"gender\":\"nan\",\"age\":23}";
        Student student = JSONUtil.toBean(a, Student.class);
        System.out.println(student);


    }
    @Test
    public void testJsonToList() {
        String jsonStr = "[{\"sno\":20131210,\"sname\":\"无忌\",\"gender\":\"男\",\"age\":25},{\"sno\":20131223,\"sname\":\"敏敏\",\"gender\":\"女\",\"age\":20}]";
        //List<Student> students = JSONUtil.parseArray(jsonStr).toList(Student.class);
        //students.forEach(System.out::println);
        JSONUtil.parseArray(jsonStr).toList(Student.class).forEach(System.out::println);
    }
    @Test
    public void testObjectToJson() {
        Student student = new Student(20131210, "无忌", "男", 25);
        System.out.println(JSON.toJSONString(student));
    }
    @Test
    public void testJsonToObject() {
        String jsonStr = "{\"age\":25,\"gender\":\"男\",\"sname\":\"无忌\",\"sno\":20131210}";
        Student student = JSON.parseObject(jsonStr, Student.class);
        System.out.println(student);
    }
    @Test
    public void testListToJson() {
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );
        System.out.println(JSON.toJSONString(students));
        System.out.println(JSON.toJSONString(students, JSONWriter.Feature.PrettyFormat));
    }
    @Test
    public void testMapToJson() {
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );
        Map<String, Student> map = students.stream().collect(Collectors.toMap(stu -> stu.getSno() + "", stu -> stu));

        System.out.println(JSON.toJSONString(map));
        System.out.println(JSON.toJSONString(map, JSONWriter.Feature.PrettyFormat));
    }

}
